/**
*  
* @Function 共享申请Controller 
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.controller    
* @FileName ShareContentApplyController.java    
* @Date 2018年9月11日下午2:54:49
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/
package com.py.credit.controller;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.ShareContentApplyEntity;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ShareApplyFieldsEnum;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.ShareContentApplyService;
import com.py.credit.utils.DateUtil;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 
 * @Function 共享申请Controller
 * @ClassName ShareContentApplyController
 * @Date 2018年9月11日 下午2:54:49
 * @Author Min DongXv
 * 
 */
@RestController
@RequestMapping(value = "/shareApply")
public class ShareContentApplyController extends BaseController {

	private static final String SHARE_CONTENT_APPLY_ID = "SHARE_CONTENT_APPLY_ID";

	@Autowired
	private ShareContentApplyService shareContentApplyService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<List<OptionalColumn>>(ShareApplyFieldsEnum.getOptionalColumns());
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<List<OptionalColumn>>(ShareApplyFieldsEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ShareContentApplyController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
			MapCache.set(userInfo.getId() + "_" + SHARE_CONTENT_APPLY_ID, columns);
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return new RestServiceResult<String>();
	}

	/**
	 * 
	 * @api {get} /shareApply/shareApplyList.json 一站式申请列表
	 * @apiName shareApplyList
	 * @apiVersion 0.0.1
	 * @apiGroup 一站式查询
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"id":1,"verifyId":null,"deptName":"信用中心","applyContent":"1","shareDate":1536681600000,"verifyName":"","verifyTime":null,"verifyStatus":"R"}]}
	 */
	@RequestMapping(value = "/shareApplyList.json")
	public RestServiceResult<List<Map<String, Object>>> shareApplyList(HttpServletRequest request,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + SHARE_CONTENT_APPLY_ID);
			List<String> showColumns = (configColumns == null || configColumns.length == 0)
					? ShareApplyFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
			// 获取列表数据
			List<Map<String, Object>> data = shareContentApplyService.shareApplyListByConditionForPage(userInfo,
					showColumns, new String[] { "id", "verifyId" }, condition, page);
			if (!CollectionUtils.isEmpty(data)) {
				Set<Integer> userIds = new HashSet<Integer>(data.size());
				String officeName = userInfo.getOfficeName();
				for (Map<String, Object> m : data) {
					m.put("deptName", officeName);
					if (null != m && m.containsKey("verifyId") && null != m.get("verifyId")) {
						userIds.add(Integer.parseInt(String.valueOf(m.get("verifyId"))));
					}
				}
				remoteBaseService.matchUserName(data, result, token, userIds, "verifyId", "verifyName");
			}
			result.setCount(page.getTotalCount());
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("ShareContentApplyController#shareApplyList", "获取共享申请列表数据异常！ERROR：" + e.getMessage(),
					e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取共享申请列表数据异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /shareApply/addShareApply.json 新增共享申请
	 * @apiName addShareApply
	 * @apiVersion 0.0.1
	 * @apiGroup 一站式查询
	 * @apiParam {String} applyContent
	 * @apiParam {String} shareDate
	 * @apiParamExample {json} 请求参数示例
	 *                  {"applyContent":"申请事由","shareDate":"2018-09-10"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/addShareApply.json")
	public RestServiceResult<Object> addShareApply(HttpServletRequest request,
			@RequestParam(value = "applyContent", defaultValue = "", required = true) String applyContent,
			@RequestParam(value = "shareDate", defaultValue = "", required = true) String shareDate) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		if (StringUtils.isNotBlank(applyContent) && StringUtils.isNotEmpty(shareDate)) {
			ShareContentApplyEntity entity = new ShareContentApplyEntity();
			entity.setApplyContent(applyContent);
			DateUtil du = DateUtil.getInstance();
			entity.setDeptId(userInfo.getOfficeId());
			entity.setManagerId(userInfo.getId());
			// 获取顶级部门
			Long topDeptId = userInfo.getOfficeId();
			String pIds = userInfo.getAllParentId();
			if (StringUtils.isNotBlank(pIds)) {
				String t = StringUtils.split(pIds, ",")[0];
				topDeptId = StringUtils.isNotBlank(t) ? Long.valueOf(t) : topDeptId;
			}
			entity.setTopDeptId(topDeptId);
			try {
				entity.setShareDate(du.strToDate(shareDate, DateUtil.YYYY_MM_DD));
				// 新增共享申请
				shareContentApplyService.addShareApply(entity);
				// 新增成功
				if (null != entity.getId()) {
					String accessKey = UuidUtil.getInstance().getUUid();
					// 发起工作流
					remoteBaseService.addWorkFlow("shareApply", accessKey, "", null, String.valueOf(entity.getId()),
							userInfo.getOfficeName() + "-共享查询申请", "", "8", null);
				}
				return result;
			} catch (Exception e) {
				ExceptionLogger.error("ShareContentApplyController#addShareApply", "新增共享申请异常！ERROR：" + e.getMessage(),
						e);
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("新增共享申请异常！");
				return result;
			}
		} else {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("请填写必填字段！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /shareApply/shareApplyDetail.json 查询共享详情
	 * @apiName shareApplyDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 一站式查询
	 * @apiParam {Long} id 共享申请ID
	 * @apiParamExample {json} 请求参数示例 {"id":1}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"id":1,"deptId":1,"deptName":"工商部门","applyContent":"1","shareDate":1536681600000,"verifyId":null,"verifyName":null,"verifyTime":null,"verifyStatus":"R"}}
	 */
	@RequestMapping(value = "/shareApplyDetail.json")
	public RestServiceResult<ShareContentApplyEntity> shareApplyDetail(HttpServletRequest request,
			@RequestParam(value = "id", defaultValue = "", required = true) Long id) {
		RestServiceResult<ShareContentApplyEntity> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			ShareContentApplyEntity entity = shareContentApplyService.shareApplyDetail(id);
			result.setData(entity);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("ShareContentApplyController#shareApplyDetail", "查询共享申请详情异常！ERROR：" + e.getMessage(),
					e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("查询共享申请详情异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /shareApply/customizeHistory.json 共享申请历史
	 * @apiName customizeHistory
	 * @apiVersion 0.0.1
	 * @apiGroup 一站式查询
	 * @apiParam {long} topDeptId 顶级部门ID
	 * @apiParamExample {json} 请求参数示例 {"topDeptId":1}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":[{"deptName":"工商部门","shareDate":1536681600000,"createTime":1536731519000,"applyContent":"1","deptId":1}]}
	 */
	@RequestMapping(value = "/customizeHistory.json")
	public RestServiceResult<List<Map<String, Object>>> customizeHistory(
			@RequestParam(value = "topDeptId") Long topDeptId) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		try {
			List<Map<String, Object>> data = shareContentApplyService.getShareApplyByDeptId(topDeptId);
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("ShareContentApplyController#customizeHistory", "共享申请历史异常！ERROR：" + e.getMessage(),
					e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("查询共享申请历史异常！");
			return result;
		}
	}

	@RequestMapping(value = "/export")
	public RestServiceResult<List<Map<String, Object>>> export(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<OptionalColumn> optionalColumns = ShareApplyFieldsEnum.getOptionalColumns();
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ShareContentApplyController#export", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			// 获取列表数据
			List<Map<String, Object>> data = shareContentApplyService.shareApplyListByConditionForPage(userInfo,
					showColumns, new String[] { "id", "verifyId" }, condition, page);
			if (!CollectionUtils.isEmpty(data)) {
				Set<Integer> userIds = new HashSet<Integer>(data.size());
				String officeName = userInfo.getOfficeName();
				for (Map<String, Object> m : data) {
					m.put("deptName", officeName);
					if (null != m && m.containsKey("verifyId") && null != m.get("verifyId")) {
						userIds.add(Integer.parseInt(String.valueOf(m.get("verifyId"))));
					}
				}
				remoteBaseService.matchUserName(data, result, token, userIds, "verifyId", "verifyName");
			}
			ExcelUtil.downloadExcel(response, data, "共享申请", "共享申请", showColumns, optionalColumns);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("共享申请导出异常，请稍后再试！");
			ExceptionLogger.error("共享申请导出异常！", e.getMessage(), e);
			return result;
		}
	}
}
